package com.auditlog.sample.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.auditlog.datasource.struct.FieldChangeLog;
import com.auditlog.datasource.struct.RowChangeLog;
import com.auditlog.datasource.table.ColumnMeta;
import com.auditlog.datasource.table.TableMeta;
import com.auditlog.datasource.table.cache.TableMetaCache;
import com.auditlog.datasource.table.cache.TableMetaCacheFactory;
import com.auditlog.listener.TableChangeEvent;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CustomStorageHandler implements com.auditlog.handler.storage.StorageHandler {
    @Override
    public boolean store(TableChangeEvent event) {
        TableMetaCache tableMetaCache = TableMetaCacheFactory.getTableMetaCache(event.getDbType());
        event.getTableChangeLogs().forEach(e -> {
            String tableName = e.getTableName();
            TableMeta tableMeta = tableMetaCache.getTableMeta(null, tableName, event.getResourceId());
            List<RowChangeLog> rowChangeLogs = e.getRowChangeLogs();
            rowChangeLogs.forEach(row -> {
                List<FieldChangeLog> fieldChangeLogs = row.getFieldChangeLogs();
                fieldChangeLogs.forEach(col -> {
                    String name = col.getName();
                    ColumnMeta columnMeta = tableMeta.getColumnMeta(name);
                    String remarks = columnMeta.getRemarks();
                    if(StrUtil.isNotEmpty(remarks)) {
                        col.setName(remarks);
                    }
                });
            });
        });
        System.out.println(JSONUtil.toJsonStr(event));
        return true;
    }
}
